package client.comm.baoding.ui

import android.annotation.SuppressLint
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.view.View
import android.view.ViewGroup
import android.webkit.*
import androidx.annotation.RequiresApi
import client.comm.baoding.BaseMiddleActivity
import client.comm.baoding.R
import client.comm.baoding.databinding.ActivityWebPayBinding
import client.comm.baoding.ui.vm.NullViewModel
import client.comm.commlib.widget.EmptyLayout

class WebPayActivity : BaseMiddleActivity<NullViewModel, ActivityWebPayBinding>() {

    override fun getLayout(): Int {
        return R.layout.activity_web_pay
    }

    var title: String? = ""
    var url: String? = ""
//    var html: String? = ""

    override fun initViewModel(): NullViewModel = createViewModel()

    override fun initView() {
        binding.event = this
        title = intent.getStringExtra("title")
        url = intent.getStringExtra("adInfo")
        //html = intent.getStringExtra("html")
        binding.title = (title)

        val mWebSettings = binding.wvShow.settings
        mWebSettings.setJavaScriptEnabled(true)
        mWebSettings.setBuiltInZoomControls(false)
        mWebSettings.setLightTouchEnabled(true)
        // 使用localStorage则必须打开
        mWebSettings.setDomStorageEnabled(true)
        mWebSettings.setSupportZoom(false)

        //0525
        mWebSettings.setUseWideViewPort(true);
        mWebSettings.setLoadWithOverviewMode(true);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
        } else {
            mWebSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }

//        // 设置可以访问文件
        mWebSettings.setAllowFileAccess(true);
//        // 设置支持缩放
//        mWebSettings.setBuiltInZoomControls(true);
        mWebSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
//        mWebSettings.setGeolocationEnabled(true);

        binding.wvShow.isHapticFeedbackEnabled = false
//        getHtmlData(html!!)!!
//        binding.wvShow.loadDataWithBaseURL("https://cashier1.sandpay.com.cn/",html!!, "text/html;charset=utf-8","utf-8",null);

        url?.let {
            binding.wvShow.loadUrl(url!!)
        }


        binding.wvShow.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String?): Boolean {
                try {
                    if (url!!.startsWith("weixin://")
                        || url!!.startsWith("alipays://")
                        || url!!.startsWith("bestpay://")
                    ) {

                        val intent = Intent()
                        intent.action = Intent.ACTION_VIEW
                        intent.data = Uri.parse(url)
                        startActivity(intent)
                        return true
                    }
                } catch (e: Exception) {
                    return false
                }
                url?.let {
                    if (url.endsWith("android_asset/return_index.html")) {
                        view.loadUrl("file:///android_asset/return_index.html")
                    } else
                        view.loadUrl(url)
                }
                return true
            }


            override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {
                super.onPageStarted(view, url, favicon)
            }

            @RequiresApi(Build.VERSION_CODES.KITKAT)
            override fun onPageFinished(view: WebView?, url: String?) {
                super.onPageFinished(view, url)
                binding.emptyLayout.visibility = View.GONE
            }

            override fun onReceivedError(
                view: WebView?,
                request: WebResourceRequest?,
                error: WebResourceError?
            ) {
                super.onReceivedError(view, request, error)
//                binding.emptyLayout.errorType = EmptyLayout.NETWORK_ERROR

            }
        }
        setFun()
    }

    @SuppressLint("JavascriptInterface")
    fun setFun() {
        binding.wvShow.addJavascriptInterface(this, "android")
    }


    @JavascriptInterface
    fun backCall() {
        finish()
    }

    private fun getHtmlData(bodyHTML: String): String? {
        val head = "<head>" +
                "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\"> " +
                "<style>html{padding:15px;} body{word-wrap:break-word;font-size:13px;padding:0px;margin:0px} p{padding:0px;margin:0px;font-size:13px;color:#222222;line-height:1.3;} img{padding:0px,margin:0px;max-width:100%; width:auto; height:auto;}</style>" +
                "</head>"
        return "<html>$head<body>$bodyHTML</body></html>"
    }


    override fun onDestroy() {
        if (binding.wvShow != null) {
//            binding.wvShow.setWebViewClient(null)
            binding.wvShow.setWebChromeClient(null)
//            binding.wvShow.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            binding.wvShow.clearHistory()
            (binding.wvShow.getParent() as ViewGroup).removeView(binding.wvShow)
            binding.wvShow.destroy()
//            binding.wvShow = null
        }
        setResult(0x999)
        super.onDestroy()
    }

}